/**
 * 
 */
package vn.smartware.co.framework.action;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vn.smartware.co.framework.config.SystemConfig;
import vn.smartware.co.framework.db.factory.JDBCFactory;
import vn.smartware.co.framework.exception.ServerException;
import vn.smartware.co.framework.form.ActionForm;


/**
 * BaseAction
 * @author thuctt
 */
public abstract class BaseAction {
    
    private ServletContext context;
    
	/**
	 * execute
	 * @param request
	 * @param responce
	 * @param mapping
	 * @param form
	 * @return ActionForm
	 */
	public ActionForm execute(HttpServletRequest request, 
			                     HttpServletResponse responce, 
					             SystemConfig mapping, ActionForm form) {
		return null;
	}

	/**
	 * @return the context
	 */
	public ServletContext getContext() {
		return this.context;
	}

	/**
	 * @param context the context to set
	 */
	public void setContext(ServletContext context) {
		this.context = context;
	}
	
	/**
	 * get connection
	 * @return Connection
	 * @throws ServerException
	 */
	protected Connection getConnection() throws ServerException {
		
		try {
			Connection conn = JDBCFactory.createConnection();
			return conn;
			
		}catch (Exception e) {
			throw new ServerException(e.getCause().getMessage());
		}
	}
	
	/**
	 * commit
	 * 
	 * @param conn
	 * @throws ServerException
	 */
	protected void commit(Connection conn) throws ServerException {
		
		try {
			JDBCFactory.commit(conn);
			
		} catch (SQLException e) {
			throw new ServerException(e.getCause().getMessage());
		}
	}
	
	/**
	 * rollback
	 * 
	 * @param conn
	 * @throws ServerException
	 */
	protected void rollback(Connection conn) throws ServerException {
		
		try {
			JDBCFactory.rollback(conn);
			
		} catch (SQLException e) {
			throw new ServerException(e.getCause().getMessage());
		}
	}
	
	/**
	 * close connection
	 * 
	 * @param conn
	 * @throws ServerException
	 */
	protected void closeConnection(Connection conn) throws ServerException {
		
		try {
			JDBCFactory.closeConnection(conn);
			
		} catch (SQLException e) {
			throw new ServerException(e.getCause().getMessage());
		}
	}
}
